<!--
 * @Description:用户管理页面
-->
<template>
  <div class="staff-manage">
    <ActionBar
      :add-active="addActive"
      :del-active="delActive"
      :edit-active="editActive"
      :cancel-active="cancelActive"
      :save-active="saveActive"
      :func-auth-active="funcAuthActive"
      :data-auth-active="dataAuthActive"
      :assign-role="assignRoleActive"
      :has-func-auth="false"
      :has-data-auth="false"
      :has-assign-role="true"
      @funcAuth="funcAuthShow"
      @dataAuth="dataAuthShow"
      @assignRole="assignRoleShow('formData')"
      @add="add"
      @cancel="cancel('formData')"
      @edit="edit"
      @del="del"
      @save="save('formData')"
    />
    <div class="common-layout">
      <div class="search-box">
        <div class="label-input mr-20">
          <div class="label">用户名称</div>
          <div class="input">
            <el-input v-model="username" clearable />
          </div>
        </div>
        <div class="search ml-20">
          <img src="~@/assets/action-bar-icon/search.png" @click="search" />
        </div>
      </div>
      <div class="content">
        <div class="table-box">
          <el-table
            v-loading="loading"
            highlight-current-row
            :data="tableData"
            stripe
            border
            height="82%"
            @row-click="handleEdit"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" label="序号" width="100" />
            <el-table-column prop="username" label="姓名" />
            <el-table-column prop="phone" label="手机号" />
          </el-table>
          <Pagination
            :page-size="pageSize"
            :current-page="currentPage"
            :total-size="totalSize"
            @changePageSize="changePageSize"
            @changeCurrentPage="changeCurrentPage"
          />
        </div>

        <div class="form">
          <funcAuthComponent
            v-if="nowpage === 2"
            ref="funcAuth"
            :userid="formData.id"
          />
          <dataAuthComponent
            v-if="nowpage === 3"
            ref="dataAuth"
            :userid="formData.id"
          />
          <assignroleComponent
            v-if="nowpage === 4"
            ref="assignrole"
            :userid="formData.id"
          />
          <el-form
            v-if="nowpage === 1"
            ref="formData"
            label-position="left"
            :model="formData"
            :rules="rules"
            class="el-form"
          >
            <el-form-item label="用户名:" prop="username" class="w100p">
              <el-input
                v-model="formData.username"
                :disabled="!canInput"
                clearable
              />
            </el-form-item>
            <el-form-item v-if="nowChanceStau === 'add'" label="账号:" prop="account" class="w100p">
              <el-input
                v-model="formData.account"
                :disabled="!canInput"
                clearable
              />
            </el-form-item>
            <el-form-item v-if="nowChanceStau === 'add'" label="密码:" prop="password" class="w100p">
              <el-input
                v-model="formData.password"
                show-password
                type="password"
                :disabled="!canInput"
                clearable
              />
            </el-form-item>
            <el-form-item v-if="nowChanceStau === 'add'" label="身份证号:" prop="cardNO" class="w100p">
              <el-input
                v-model="formData.cardNO"
                placeholder="身份证号"
                :disabled="!canInput"
              />
            </el-form-item>
            <el-form-item label="手机号:" prop="phone" class="w1000p">
              <el-input
                v-model="formData.phone"
                :disabled="!canInput"
                clearable
              />
            </el-form-item>
            <el-form-item label="邮箱:" prop="email" class="w100p">
              <el-input
                v-model="formData.email"
                :disabled="!canInput"
                clearable
              />
            </el-form-item>
            <el-form-item label="性别:" prop="gender" class="w100p">
              <el-select
                v-model="formData.gender"
                clearable
                :disabled="!canInput"
              >
                <el-option label="男" value="MALE" />
                <el-option label="女" value="FEMALE" />
              </el-select>
            </el-form-item>
            <el-form-item label="微信:" prop="weChat" class="w100p">
              <el-input
                v-model="formData.weChat"
                :disabled="!canInput"
                clearable
              />
            </el-form-item>
            <el-form-item label="住址:" prop="address" class="w100p">
              <el-input
                v-model="formData.address"
                :disabled="!canInput"
                clearable
              />
            </el-form-item>
            <el-form-item label="生日:" prop="birthday" class="w100p">
              <el-date-picker
                v-model="formData.birthday"
                type="date"
                :disabled="!canInput"
                clearable
              />
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import userManage from "@/api/system-settings/user-manage";
import funcAuthComponent from "../menu-config/index";
import dataAuthComponent from "../components/data-auth-componet";
import assignroleComponent from "../components/assign-rolle-component";
import axios from "axios";
import { getToken } from "@/utils/auth";

import { mymixin } from "@/utils/mixin";
export default {
  name: "UserManage",
  components: {
    ActionBar,
    Pagination,
    funcAuthComponent,
    dataAuthComponent,
    assignroleComponent
    // bottomLefttwochart
  },
  mixins: [mymixin],
  data() {
    var checkIdentitytionId = (rule, value, callback) => {
      const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      if (value === '' || value === undefined || value === null) {
        callback();
      } else {
        if ((!reg.test(value)) && value !== '') {
          callback(new Error('请输入正确的身份证号码'));
        } else {
          callback();
        }
      }
    };
    return {
      // 右侧权限展示1主界面,2功能权限,3数据权限,4分配角色
      nowpage: 1,
      // 操作按钮的逻辑及展示数据
      addActive: true,
      editActive: false,
      delActive: false,
      saveActive: false,
      cancelActive: false,
      funcAuthActive: false,
      // 数据权限
      dataAuthActive: false,
      // 分配角色
      assignRoleActive: false,
      // table
      loading: true,
      // 当前页
      currentPage: 1,
      // 每页的数据条数
      pageSize: 10,
      // 总条数
      totalSize: 0,
      // 员工姓名
      username: "",
      // 是否能输入
      canInput: false,
      tableData: [],
      formData: {},
      rules: {
        username: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        account: [{ required: true, message: "请输入账号", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        // gender: [{ required: true, message: "请输入性别", trigger: "blur" }],
        cardNO: [
          { required: true, message: "请输入身份证", trigger: "blur" },
          { validator: checkIdentitytionId, trigger: "blur" }
        ],
        phone: [
          { required: true, message: "请输入联系方式", trigger: "blur" },
          {
            pattern: /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/,
            message: "请输入合法手机号/电话号",
            trigger: "blur"
          }
        ]
      },
      // 选中的数据项数组 employeeId组成 (此数组最多为一个)
      selectedStaffList: []
    };
  },
  watch: {},
  created() {
    // 获取表格数据
    this.getTableDataList();
  },
  mounted() {},
  methods: {
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        username: this.username,
        notAdmin: true
      };
      userManage.getUserStaffList(params).then((res) => {
        this.loading = false;
        let data = res.data;
        // console.log(data);
        // 赋值总条数
        this.totalSize = data.totalElements;
        // 赋值数组
        this.tableData = data.content;
        this.addblankmet()
        this.resetActionBar();
      });
    },
    // 填充表格空白行
    addblankmet() {
      let havline = this.tableData.length % this.pageSize
      if (this.tableData.length < this.pageSize) {
        if (havline < this.pageSize) {
          const remain = this.pageSize - havline;
          for (var i = 0; i < remain; i++) {
            this.tableData.push({ 'indflag': i + this.tableData.length - 1 });
          }
        }
      }
    },
    // 初始化操作栏状态
    resetActionBar() {
      this.nowChanceStau = ''
      this.addActive = true;
      this.editActive = false;
      this.delActive = false;
      this.saveActive = false;
      this.funcAuthActive = false;
      this.dataAuthActive = false;
      this.assignRoleActive = false;
      this.cancelActive = false;
      this.canInput = false;
      this.formData = {};
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    handleEdit(row) {
      this.nowpage = 1;
      // TODO 点击行元素后 edit
      // this.formData = {}
      this.nowChanceStau = ''
      this.formData = JSON.parse(JSON.stringify(row));
      // console.log(this.formData);
      // this.formData.employeeId = row.employeeId;
      this.editActive = true;
      this.funcAuthActive = true;
      this.addActive = true;
      this.dataAuthActive = true;
      this.assignRoleActive = true;
      this.saveActive = false;
      this.cancelActive = true;
      this.canInput = false;
      // this.$refs.formData.resetFields();
    },
    handleSelectionChange(list) {
      this.selectedStaffList = [];
      this.selectedStaffList = list.map((item) => item.employeeId);
      if (this.selectedStaffList.length > 0) this.delActive = true;
      else this.delActive = false;

      // 多个处理为单个数据
      if (this.selectedStaffList.length > 1) {
        this.$message.warning("员工不可多选删除！");
        this.selectedStaffList.splice(0, this.selectedStaffList.length - 1);
        console.log(this.selectedStaffList);
      }
    },
    // 点击功能权限触发的方法
    funcAuthShow() {
      this.nowpage = 2;
      this.cancelActive = true;
      this.addActive = false;
      this.editActive = false;
      console.log("点击了功能权限");
      this.saveActive = true;
    },
    // 点击数据权限触发的方法
    dataAuthShow() {
      this.nowpage = 3;
      this.cancelActive = true;
      this.addActive = false;
      this.editActive = false;
      console.log("点击了数据权限");
      this.saveActive = true;
    },
    // 点击了分配角色
    assignRoleShow() {
      this.nowpage = 4;
      this.cancelActive = true;
      this.addActive = false;
      this.editActive = false;
      console.log("点击了分配角色");
      this.saveActive = true;
    },
    // add() {
    //   // TODO 添加后 input可输入 add及cancel 1 其余 0
    //   this.canInput = true;
    //   this.addActive = false;
    //   this.editActive = false;
    //   this.delActive = false;
    //   this.saveActive = true;
    //   this.cancelActive = true;
    //   // inspectionRouteId置空
    //   this.formData.inspectionRouteId = "";
    // },
    // edit() {
    //   // TODO 编辑后 input可输入 save及cancel 1 其余 0
    //   this.canInput = true;
    //   this.addActive = false;
    //   this.editActive = false;
    //   this.delActive = false;
    //   this.saveActive = true;
    //   this.cancelActive = true;
    // },
    del() {
      this.$message.warning("用户不允许删除");
      // userManage
      //   .delInspectionRouteInfo(this.inspectionRouteIdList)
      //   .then(res => {
      //     if (res.code === 1) {
      //       this.$message.success(res.msg);
      //       this.getTableDataList();
      //     }
      //   });
    },
    cancel(formData) {
      // TODO 取消后 除了查看二维码外 input不可输入 add 1 其余 0
      this.nowChanceStau = ''
      this.canInput = false;
      this.addActive = true;
      this.editActive = false;
      this.delActive = false;
      this.saveActive = false;
      this.cancelActive = false;
      this.dataAuthActive = false;
      this.funcAuthActive = false;
      this.assignRoleActive = false;
      this.nowpage = 1;
      this.formData.employeeId = "";
      // if (formData) {
      //   this.$refs[formData].resetFields();
      // }
    },
    save(formData) {
      if (this.formData.id && this.nowpage === 2) {
        this.$refs.funcAuth.setpermission();
      } else if (this.nowpage === 3) {
        this.$refs.dataAuth.setpermission();
      } else if (this.nowpage === 4) {
        this.$refs.assignrole.checkchange();
      }
      if (!formData) return
      this.$refs[formData].validate(valid => {
        if (valid) {
          // if (this.add) {
          //   console.log('1')
          // } else if (this.edit) {
          //   console.log('2')
          // }
          // this.formData["birthday"] = this.dateToFormat(this.formData["birthday"]);
          if (this.nowChanceStau === "edit" && this.nowpage === 1) {
            // 编辑接口
            // 巡检点数组赋值进formData
            // this.formData.routePointMapperList = this.tagsList;
            // console.log(this.formData);
            userManage.editUserInfo(this.formData).then((res) => {
              if (res.code === 1) {
                this.$message.success("修改成功！");
                this.resetActionBar();
                this.getTableDataList();
              }
            });
          } else if (this.nowChanceStau === "add" && this.nowpage === 1) {
            // 新增接口
            this.formData.organizationNo = getToken('organizationNo');
            this.formData.pass = false;
            this.formData.companyId = getToken('companyId');
            this.formData.vCode = getToken('companyId');
            this.registerIofo(this.formData)
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },
    registerIofo(params, sysDataBaseName) {
      let zhurl = this.$baseurl.webServiceUrl + 'oa/oauth/register'
      axios({
        method: "POST",
        url: zhurl,
        headers: {
          databaseName: getToken("databaseName"),
          accessToken: getToken("token"),
          sysDataBaseName: sysDataBaseName,
          organizationList: getToken('organizationList'),
          organizationNo: getToken('organizationNo')
        },
        data: {
          ...params
        }
      }).then(res => {
        if (res.data.code === 1) {
          let formData = {
            ...this.formData,
            pass: true,
            expired: true
          }
          this.regerIofo(formData, 'DB_TDW1_SC')
          this.regerIofo(formData, 'DB_TDW1_OM1')
          this.getTableDataList();
          this.$message.success("添加成功");
        } else {
          this.$message.warning("添加失败");
        }
      });
    },
    regerIofo(params, sysDataBaseName) {
      let zhurl = this.$baseurl.webServiceUrl + 'oa/oauth/registerSysUser'
      axios({
        method: "POST",
        url: zhurl,
        headers: {
          databaseName: getToken("databaseName"),
          accessToken: getToken("token"),
          sysDataBaseName: sysDataBaseName,
          organizationList: getToken('organizationList'),
          organizationNo: getToken('organizationNo')
        },
        data: {
          ...params
        }
      }).then(res => {
        if (res.data.code === 1) {
          // this.$message.success("添加成功");
        } else {
          // this.$message.warning("删除失败");
        }
      });
    }

  }
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";
.staff-manage {
  width: 100%;
  height: 100%;
  ::v-deep .el-form-item__content {
    display: flex;
    align-items: center;
  }
  ::v-deep .el-form-item__label {
    min-width: 100px;
  }
  .common-layout {
    border: 1px solid $borderColor;
    height: calc(100% - #{$actionBarHeight + 10});
    padding: 20px;
    .search-box {
      display: flex;
      align-items: center;
      .label-input {
        display: flex;
        align-items: center;
        .label {
          width: 100px;
          white-space: nowrap;
        }
      }
      .search {
        display: flex;
        align-items: center;
        img {
          height: 30px;
        }
      }
    }
    .content {
      height: calc(100% - 50px);
      margin: 20px 0;
      display: flex;
      .table-box {
        width: 50%;
        position: relative;
        height: 100%;
        overflow-y: auto;
      }
      .form {
        overflow-y: auto;
        width: 50%;
        height: 100%;
        padding-top: 20px;
        display: flex;
        justify-content: center;
        margin-left: 4%;
        border-left: dashed 1px $borderColor;
        .el-form {
          justify-content: center;
          width: 90%;
          flex-wrap: wrap;
        }
      }
    }
  }
}
</style>
